import { Modal, Form, Input } from 'antd'
import { memo, useState } from 'react'

import { postJson } from '@/utils/http/linitly.request.js'
import { successPrompt } from '@/utils/default.prompt.js'

const ChangePassword = ({
  visible,
  cancel
}) => {

  const user = JSON.parse(sessionStorage.getItem('user'))
  const [ changePasswordForm ] = Form.useForm()
  const [ confirmLoading, setConfirmLoading ] = useState(false)

  return (
    <Modal width={600} title="修改密码" visible={visible} confirmLoading={confirmLoading} onCancel={cancel}
    onOk={changePassword} destroyOnClose>
      <Form form={changePasswordForm} autoComplete="off" style={{padding: '24px 24px 0 0'}} labelCol={{ span: 4 }}
      preserve={false} name="changePasswordForm" >
        <Form.Item label="原密码" name="beforePassword" rules={[ {required: true, message: '请输入原密码'} ]}>
          <Input placeholder="请输入原密码" />
        </Form.Item>
        <Form.Item label="密码" name="password" dependencies={['password']} rules={[
          {required: true, message: '请输入密码'},
          { pattern: /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z\W]{8,}$/, message: '密码格式错误，需要至少8位的数字和字母组合' }
        ]}>
          <Input.Password placeholder="请输入密码" />
        </Form.Item>
        <Form.Item label="确认密码" name="confirmPassword" rules={[
          {required: true, message: '请输入确认密码'},
          ({ getFieldValue }) => ({
            validator(_, value) {
              if (!value || getFieldValue('password') === value) {
                return Promise.resolve();
              }
              return Promise.reject(new Error('两次密码输入不一致'));
            },
          }),
        ]}>
          <Input.Password placeholder="请再次确认密码" />
        </Form.Item>
       </Form>
    </Modal>
  )

  function changePassword() {
    changePasswordForm.validateFields().then(values => {
      setConfirmLoading(true)
      postJson('/sysAdminUser/changePassword', {
        id: user.id,
        ...values
      }).then(() => {
        successPrompt('修改密码成功')
        cancel()
      }).finally(() => {
        setConfirmLoading(false)
      })
    })
  }
}

export default memo(ChangePassword)
